package com.fengchao.api.service;

import com.alibaba.fastjson.JSON;
import com.fengchao.api.config.Constant;
import com.fengchao.api.dao.bci.BciArtistInfoMapper;
import com.fengchao.api.dao.sam.SamArtistMessageCommentMapper;
import com.fengchao.api.dao.sam.SamArtistMessageMapper;
import com.fengchao.api.dao.usr.UsrInfoMapper;
import com.fengchao.api.dao.usr.UsrPersonalMessageMapper;
import com.fengchao.api.dao.usr.UsrSharedMessageOptInMapper;
import com.fengchao.api.dao.usr.UsrUserFocusArtistMapper;
import com.fengchao.model.bci.BciArtistInfo;
import com.fengchao.model.entity.comm.CustomBizException;
import com.fengchao.model.sam.SamArtistMessage;
import com.fengchao.model.sam.SamArtistMessageComment;
import com.fengchao.model.usr.UsrInfo;
import com.fengchao.model.usr.UsrSharedMessageOptIn;
import com.fengchao.util.common.CommonValidator;
import com.fengchao.util.net.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.alibaba.fastjson.JSON.parseObject;
import static java.awt.SystemColor.info;

/**
 * 艺人动态
 * Created by http://my.oschina.net/wangnian on 2016/8/10.
 */

@Service
public class SamService {

    @Autowired
    private SamArtistMessageMapper samArtistMessageMapper;
    @Autowired
    private BciArtistInfoMapper bciArtistInfoMapper;
    @Autowired
    private UsrUserFocusArtistMapper usrUserFocusArtistMapper;
    @Autowired
    private UsrSharedMessageOptInMapper usrSharedMessageOptInMapper;
    @Autowired
    private UsrInfoMapper usrInfoMapper;
    @Autowired
    private SamArtistMessageCommentMapper samArtistMessageCommentMapper;

    private static Logger logger = LoggerFactory.getLogger(SamService.class);

    /**
     * 获取全部艺人动态
     *
     * @param page
     * @param count
     * @return
     */
    public List<Map<String, Object>> findSamArtistMessageAll(Integer userId, Integer page, Integer count) {
        Integer start = (page - 1) * count;
        List<SamArtistMessage> samArtistMessages = samArtistMessageMapper.findSamArtistMessageAll(start, count);
        return forSamArtistMessage(samArtistMessages, userId);
    }


    /**
     * 获取全部艺人动态条数
     *
     * @return
     */
    public Integer findSamArtistMessageAllTotal() {
        return samArtistMessageMapper.findSamArtistMessageAllTotal();
    }

    /**
     * 获取userId关注艺人动态
     *
     * @param page
     * @param count
     * @return
     */
    public List<Map<String, Object>> findSamArtistMessageByArtists(Integer userId, Integer page, Integer count) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        Integer start = (page - 1) * count;
        List<Integer> artistIds = usrUserFocusArtistMapper.findArtistIdByUserId(userId);
        if (artistIds == null || artistIds.size() == 0) {
            return resultList;
        }
        List<SamArtistMessage> samArtistMessages = samArtistMessageMapper.findSamArtistMessageByArtistIds(start, count, artistIds);
        return forSamArtistMessage(samArtistMessages, userId);
    }

    /**
     * 获取userId关注艺人动态条数
     *
     * @return
     */
    public Integer findSamArtistMessageByArtistsTotal(Integer userId) {
        List<Integer> artistIds = usrUserFocusArtistMapper.findArtistIdByUserId(userId);
        if (artistIds == null || artistIds.size() == 0) {
            return 0;
        }
        Integer total = samArtistMessageMapper.findSamArtistMessageByArtistIdsTotal(artistIds);
        return total;
    }

    /**
     * 获取某个艺人的动态
     *
     * @param page
     * @param count
     * @return
     */
    public List<Map<String, Object>> findSamArtistMessageByArtist(Integer userId, Integer artistId, Integer page, Integer count) {
        Integer start = (page - 1) * count;
        List<SamArtistMessage> samArtistMessages = samArtistMessageMapper.findSamArtistMessageByArtistId(start, count, artistId);
        return forSamArtistMessage(samArtistMessages, userId);
    }

    /**
     * 获取某个艺人的动态条数
     *
     * @return
     */
    public Integer findSamArtistMessageByArtistTotal(Integer artistId) {
        return samArtistMessageMapper.findSamArtistMessageByArtistIdTotal(artistId);
    }

    /**
     * 获取我的动态
     *
     * @param page
     * @param count
     * @return
     */
    public List<Map<String, Object>> findSamArtistMessageByUserId(Integer userId, Integer page, Integer count) {
        BciArtistInfo bciArtistInfo = bciArtistInfoMapper.findArtistByUserId(userId);
        if (bciArtistInfo == null) {
            return new ArrayList<>();
        }
        Integer start = (page - 1) * count;
        List<SamArtistMessage> samArtistMessages = samArtistMessageMapper.findSamArtistMessageByArtistId(start, count, bciArtistInfo.getId());
        return forSamArtistMessage(samArtistMessages, userId);
    }

    /**
     * 根据id查询动态
     *
     * @param messageId
     * @return
     */
    public Map<String, Object> findSamArtistMessageById(Integer messageId) {
        SamArtistMessage samArtistMessage = samArtistMessageMapper.selectByPrimaryKey(messageId);
        if (samArtistMessage == null) {
            return new HashMap<>();
        }
        Map<String, Object> resultMap = new HashMap();
        BciArtistInfo bciArtistInfo = bciArtistInfoMapper.selectByPrimaryKey(samArtistMessage.getArtistId());
        resultMap.put("id", samArtistMessage.getId()); //分享的ID
        resultMap.put("artistId", bciArtistInfo.getId());//艺人id
        resultMap.put("headIcon", bciArtistInfo.getHeadIconApp());
        resultMap.put("sharedVideoImage", bciArtistInfo.getSharedVideoImage());
        resultMap.put("nameDisplay", bciArtistInfo.getNameDisplay());
        resultMap.put("style", bciArtistInfo.getMusicStyle());
        resultMap.put("nationality", bciArtistInfo.getNationality());//艺人的国籍
        resultMap.put("createTime", samArtistMessage.getCreateTime());
        resultMap.put("sharedMessage", samArtistMessage.getSharedMessage()); //分享的消息
        resultMap.put("sharedCount", samArtistMessage.getSharedCount());//分享的次数
        resultMap.put("optInCount", samArtistMessage.getOptInCount());//点赞的次数
        resultMap.put("sharedImageUrl", samArtistMessage.getSharedImageUrl() == null ? "" : samArtistMessage.getSharedImageUrl());//分享的图片链接
        resultMap.put("sharedVideoUrl", samArtistMessage.getSharedVideoUrl() == null ? "" : samArtistMessage.getSharedVideoUrl());//分享的视频链接
        return resultMap;
    }

    /**
     * 获取我的动态的条数
     *
     * @return
     */
    public Integer findSamArtistMessageByUserIdTotal(Integer userId) {
        BciArtistInfo bciArtistInfo = bciArtistInfoMapper.findArtistByUserId(userId);
        if (bciArtistInfo == null) {
            return 0;
        }
        return samArtistMessageMapper.findSamArtistMessageByArtistIdTotal(bciArtistInfo.getId());
    }

    /**
     * 封装的循环动态方法
     *
     * @return
     */
    public List<Map<String, Object>> forSamArtistMessage(List<SamArtistMessage> samArtistMessages, Integer userId) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (SamArtistMessage samArtistMessage : samArtistMessages) {
            Map<String, Object> resultMap = new HashMap();
            BciArtistInfo bciArtistInfo = bciArtistInfoMapper.selectByPrimaryKey(samArtistMessage.getArtistId());
            Integer commentCount = samArtistMessageCommentMapper.findCountByMessageId(samArtistMessage.getId());
            resultMap.put("id", samArtistMessage.getId()); //分享的ID
            resultMap.put("artistId", bciArtistInfo.getId());//艺人id
            resultMap.put("headIcon", bciArtistInfo.getHeadIconApp());
            resultMap.put("sharedVideoImage", bciArtistInfo.getSharedVideoImage());
            resultMap.put("nameDisplay", bciArtistInfo.getNameDisplay());
            resultMap.put("style", bciArtistInfo.getMusicStyle());
            resultMap.put("nationality", bciArtistInfo.getNationality());//艺人的国籍
            resultMap.put("createTime", samArtistMessage.getCreateTime());
            resultMap.put("sharedMessage", samArtistMessage.getSharedMessage()); //分享的消息
            resultMap.put("sharedCount", samArtistMessage.getSharedCount());//分享的次数
            resultMap.put("commentCount", commentCount);
            resultMap.put("optInCount", samArtistMessage.getOptInCount());//点赞的次数
            String imageUrl = samArtistMessage.getSharedImageUrl();
            resultMap.put("sharedImageUrl", samArtistMessage.getSharedImageUrl() == null ? "" : samArtistMessage.getSharedImageUrl());//分享的图片链接
            if (CommonValidator.isStringsNotNull(imageUrl)) {//取CDN上的图片 大小
                try {
                    String result = HttpUtil.get(imageUrl + "!/info");
                    Map map = JSON.parseObject(result, Map.class);
                    resultMap.putAll(map);
                } catch (Exception ex) {
                    logger.warn("图片不是本地的CDN");
                }
            }
            resultMap.put("sharedVideoUrl", samArtistMessage.getSharedVideoUrl() == null ? "" : samArtistMessage.getSharedVideoUrl());//分享的视频链接
            Integer isFocus = 0;
            if (CommonValidator.isStringsNotNull(userId)) {
                //查询该用户是否关注了该艺人
                isFocus = usrUserFocusArtistMapper.findCountByArtistId(bciArtistInfo.getId(), userId);
            }
            resultMap.put("isFocus", isFocus > 0 ? 1 : isFocus);
            UsrSharedMessageOptIn usrSharedMessageOptIn = usrSharedMessageOptInMapper.findByUserIdAndSharedMessageId(userId, samArtistMessage.getId());
            resultMap.put("isLike", usrSharedMessageOptIn == null ? 0 : 1);
            resultMap.put("sharedUrl", Constant.CONFIGMAP.get("dynDetailShare") + samArtistMessage.getId());
            resultList.add(resultMap);
        }
        return resultList;
    }

    /**
     * 添加喜欢
     *
     * @param samArtistMessageId
     * @param userId
     * @return
     */
    public boolean addLike(Integer samArtistMessageId, Integer userId) {
        SamArtistMessage samArtistMessage = samArtistMessageMapper.selectByPrimaryKey(samArtistMessageId);
        if (samArtistMessage == null) {
            return false;
        }
        //判断是否已添加为喜欢
        UsrSharedMessageOptIn usrSharedMessageOptIn = usrSharedMessageOptInMapper.findByUserIdAndSharedMessageId(userId, samArtistMessageId);
        if (usrSharedMessageOptIn == null) {//之前没有
            //添加一条 动态id和userId的关系
            UsrSharedMessageOptIn usrSharedMessageOptIn1 = new UsrSharedMessageOptIn();
            usrSharedMessageOptIn1.setCreateTime(new Date());
            usrSharedMessageOptIn1.setSharedMessageId(samArtistMessageId);
            usrSharedMessageOptIn1.setUserId(userId);
            usrSharedMessageOptInMapper.insertSelective(usrSharedMessageOptIn1);
            //将动态的点赞+1
            SamArtistMessage samArtistMessage1 = new SamArtistMessage();
            samArtistMessage1.setOptInCount(samArtistMessage.getOptInCount() + 1);
            samArtistMessage1.setId(samArtistMessage.getId());
            samArtistMessageMapper.updateByPrimaryKeySelective(samArtistMessage1);
            return true;
        } else {
            return true;
        }
    }

    /**
     * 添加分享
     *
     * @param samArtistMessageId
     * @return
     */
    public boolean addshared(Integer samArtistMessageId) {
        SamArtistMessage samArtistMessage = samArtistMessageMapper.selectByPrimaryKey(samArtistMessageId);
        if (samArtistMessage == null) {
            return false;
        }
        //将分享+1
        SamArtistMessage samArtistMessage1 = new SamArtistMessage();
        samArtistMessage1.setId(samArtistMessage.getId());
        samArtistMessage1.setSharedCount(samArtistMessage.getSharedCount() + 1);
        samArtistMessageMapper.updateByPrimaryKeySelective(samArtistMessage1);
        return true;
    }

    /**
     * 添加动态
     *
     * @param
     * @return
     */
    public boolean addMessage(Integer userId, String sharedImageUrl, String sharedVoideoUrl, String sharedMessage) {
        BciArtistInfo bciArtistInfo = bciArtistInfoMapper.findArtistByUserId(userId);
        if (bciArtistInfo == null) {
            return false;
        }
        //创建动态
        SamArtistMessage samArtistMessage1 = new SamArtistMessage();
        samArtistMessage1.setCreateTime(new Date());
        samArtistMessage1.setArtistId(bciArtistInfo.getId());
        samArtistMessage1.setSharedImageUrl(sharedImageUrl);
        samArtistMessage1.setSharedVideoUrl(sharedVoideoUrl);
        samArtistMessage1.setSharedMessage(sharedMessage);
        samArtistMessage1.setSourceMessage(sharedMessage);
        samArtistMessageMapper.insertSelective(samArtistMessage1);
        return true;
    }

    /**
     * 删除动态
     *
     * @param
     * @return
     */
    public boolean delectMessage(Integer userId, Integer samArtistMessageId) {
        BciArtistInfo bciArtistInfo = bciArtistInfoMapper.findArtistByUserId(userId);
        if (bciArtistInfo == null) {
            return false;
        }
        SamArtistMessage samArtistMessage = samArtistMessageMapper.selectByPrimaryKey(samArtistMessageId);
        if (samArtistMessage == null) {
            return false;
        }
        if (!samArtistMessage.getArtistId().equals(bciArtistInfo.getId())) {
            return false;
        }
        samArtistMessageMapper.deleteByPrimaryKey(samArtistMessageId);
        return true;
    }


    /**
     * 查询我的最新的点赞消息
     *
     * @return
     */
    public Map<Object, Object> getLikeList(Integer userId, Integer page, Integer count) {
        Map<Object, Object> map = new HashMap<>();

        BciArtistInfo bciArtistInfo = bciArtistInfoMapper.findArtistByUserId(userId);
        if (bciArtistInfo == null) {
            logger.info("该用户不是艺人");
            throw new CustomBizException("该用户不是艺人");
        }
        Integer start = (page - 1) * count;
        List<Integer> messageIds = samArtistMessageMapper.findMessageIdByArtistId(bciArtistInfo.getId());//根据艺人id查询所有的消息ID
        if (messageIds.size() == 0) {
            map.put("info", new ArrayList<>());
            map.put("total", 0);
            return map;
        }
        List<UsrSharedMessageOptIn> usrSharedMessageOptIns = usrSharedMessageOptInMapper.findOptByArtistId(messageIds, start, count);

        List<Map<String, Object>> resultList = new ArrayList<>();
        for (UsrSharedMessageOptIn usrSharedMessageOptIn : usrSharedMessageOptIns) {
            Map<String, Object> resultMap = new HashMap<>();
            UsrInfo usrInfo = usrInfoMapper.selectByPrimaryKey(usrSharedMessageOptIn.getUserId());
            if (usrInfo == null) {
                logger.warn("该用户不是艺人");
                continue;
            }
            resultMap.put("userId", usrInfo.getId());
            resultMap.put("userName", usrInfo.getNicknameToEmoji() == null ? "匿名" : usrInfo.getNicknameToEmoji());
            resultMap.put("userIcon", usrInfo.getHeadIcon() == null ? "" : usrInfo.getHeadIcon());
            resultMap.put("focusTime", usrSharedMessageOptIn.getCreateTime());
            resultMap.put("text", "给您点赞");
            resultList.add(resultMap);
        }
        //更新为最新的查看点赞的时间
        BciArtistInfo bciArtistInfo1 = new BciArtistInfo();
        bciArtistInfo1.setId(bciArtistInfo.getId());
        bciArtistInfo1.setLastOptTime(new Date());
        bciArtistInfoMapper.updateByPrimaryKeySelective(bciArtistInfo1);

        Integer total = usrSharedMessageOptInMapper.findOptByArtistIdTotal(messageIds);
        map.put("info", resultList);
        map.put("total", total);
        return map;
    }

    /**
     * 根据动态id获取评论动态接口
     * 发布评论时间 图片 评论内容 名字
     *
     * @return
     */
    public Map getCommentByMessageId(Integer messageId, Integer page, Integer count) {
        List<Map> resultList = new ArrayList<>();
        Integer start = (page - 1) * count;
        List<SamArtistMessageComment> samArtistMessageComments = samArtistMessageCommentMapper.findByMessageId(messageId, start, count);
        for (SamArtistMessageComment samArtistMessageComment : samArtistMessageComments) {
            UsrInfo usrInfo = usrInfoMapper.selectByPrimaryKey(samArtistMessageComment.getUserId());
            Map<String, Object> map = new HashMap<>();
            map.put("content", samArtistMessageComment.getCommentContent());
            map.put("time", samArtistMessageComment.getCreateTime());
            map.put("name", usrInfo.getNickname() == null ? "匿名" : usrInfo.getNickname());
            map.put("headIcon", usrInfo.getHeadIcon() == null ? "" : usrInfo.getHeadIcon());
            resultList.add(map);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("info", resultList);
        return resultMap;
    }


    /**
     * 根据动态id获取评论动态接口
     * 发布评论时间 图片 评论内容 名字
     *
     * @return
     */
    @Transactional
    public void addCommentByMessageId(Integer messageId, Integer userId, String messageContent) {
        SamArtistMessageComment samArtistMessageComment = new SamArtistMessageComment();
        samArtistMessageComment.setUserId(userId);
        samArtistMessageComment.setArtistMessageId(messageId);
        samArtistMessageComment.setCommentContent(messageContent);
        samArtistMessageComment.setCreateTime(new Date());
        samArtistMessageCommentMapper.insertSelective(samArtistMessageComment);
    }
}